package com.cyandpos.pad.activity;


import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.changyi.device.APApplication;
import com.cyandpos.pad.R;
import com.cyandpos.pad.cateringformat.CateringMainActivity;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.SktConfigConstant;
import com.cyandpos.pad.common.commondata.SktConfigIdSaleTypeConstant;
import com.cyandpos.pad.common.commondata.Urls;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.login.UpdateApp;
import com.cyandpos.pad.login.presenter.ILoginPresenter;
import com.cyandpos.pad.login.presenter.LoginPresenter;
import com.cyandpos.pad.login.view.ILoginView;
import com.cyandpos.pad.offline.offlinedb.OfflineManager;
import com.cyandpos.pad.posdata.LoadConfig;
import com.cyandpos.pad.posdata.Sktconfig;
import com.cyandpos.pad.presentation.AdPresentationUtil;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MD5Utils;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.MessageLog;
import com.cyandpos.pad.utils.log.LogUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class LoginActivity extends AppCompatActivity implements ILoginView {
    private static final String FOCUS_FLAG_USERNAME = "etUsername";
    private static final String FOCUS_FLAG_PASSWORD = "etPassword";

    @BindView(R.id.et_username_login_act)
    AutoCompleteTextView etUsername;
    @BindView(R.id.et_password_login_act)
    EditText etPassword;
    @BindView(R.id.btn_login_login_act)
    Button btnLogin;
    @BindView(R.id.btn_seven_login_act)
    Button btnSeven;
    @BindView(R.id.btn_eight_login_act)
    Button btnEight;
    @BindView(R.id.btn_nine_login_act)
    Button btnNine;
    @BindView(R.id.btn_four_login_act)
    Button btnFour;
    @BindView(R.id.btn_five_login_act)
    Button btnFive;
    @BindView(R.id.btn_six_login_act)
    Button btnSix;
    @BindView(R.id.btn_one_login_act)
    Button btnOne;
    @BindView(R.id.btn_two_login_act)
    Button btnTwo;
    @BindView(R.id.btn_three_login_act)
    Button btnThree;
    @BindView(R.id.btn_zero_login_act)
    Button btnZero;
    @BindView(R.id.btn_back_login_act)
    Button btnBack;
    @BindView(R.id.btn_sure_login_act)
    Button btnSure;


    @BindView(R.id.tv_sktno)
    TextView tvSktno;
    @BindView(R.id.tv_ip)
    TextView tvIp;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.ck_offline_settings)
    CheckBox ckOffline;//脱机
    private ProgressDialog dialog;
    private ILoginPresenter loginPresenter;
    private ArrayList<String> userList = new ArrayList<String>();
    private ArrayAdapter<String> adapter;
    private UpdateApp updateApp = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        APApplication.getInstance().addActivity(this);
        new AdPresentationUtil().initDisplayData(this);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        OfflineManager.open(this);//脱机数据库开启
        requestPermissions();//动态获取权限
        loginPresenter = new LoginPresenter(this);
        dialog = new ProgressDialog(LoginActivity.this);
        dialog.setCancelable(false);
        dialog.setMessage("Loading ....");
        CommonUtils.setNoSoftware(etUsername,LoginActivity.this,true);
        CommonUtils.hideSoftInputButWithSelection(etPassword, LoginActivity.this);
        tvVersion.setText("版本号:" + CommonUtils.getCurrentVersionName(LoginActivity.this));
        tvIp.setText("IP:" + Urls.posAddress);
        tvSktno.setText("收款台:" + ErpCommonData.sktno);
        readSettingInfoLocal();//读取本地配置文件
        adapter = new ArrayAdapter<String>(this, R.layout.simple_dropdown_item_1line_login, userList);
        etUsername.setAdapter(adapter);
        btnZero.setOnClickListener(new CalOnClickListener());
        btnOne.setOnClickListener(new CalOnClickListener());
        btnTwo.setOnClickListener(new CalOnClickListener());
        btnThree.setOnClickListener(new CalOnClickListener());
        btnFour.setOnClickListener(new CalOnClickListener());
        btnFive.setOnClickListener(new CalOnClickListener());
        btnSix.setOnClickListener(new CalOnClickListener());
        btnSeven.setOnClickListener(new CalOnClickListener());
        btnEight.setOnClickListener(new CalOnClickListener());
        btnNine.setOnClickListener(new CalOnClickListener());
        btnBack.setOnClickListener(new CalOnClickListener());
        btnSure.setOnClickListener(new CalOnClickListener());
        btnBack.setOnLongClickListener(new BackOnLongClickListener());
        btnLogin.setOnClickListener(new CalOnClickListener());
        etUsername.setOnClickListener(new CalOnClickListener());
        etPassword.setOnClickListener(new CalOnClickListener());
        setOffline();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (updateApp == null) {//检查更新
            updateApp = new UpdateApp(this);
            updateApp.doHttp();
        }
        readSettingInfoLocal();//读取本地配置文件
        etUsername.setText("");
        etPassword.setText("");
        etUsername.requestFocus();
        tvVersion.setText("版本号:" + CommonUtils.getCurrentVersionName(LoginActivity.this));
//        tvIp.setText("IP:" + Urls.posAddress);
        tvIp.setText("IP:" + CommonUtils.getIp(LoginActivity.this));
        tvSktno.setText("收款台:" + ErpCommonData.sktno);

    }
    private void readSettingInfoLocal() {
        SharedPreferences sp = getSharedPreferences("LOGIN", 0);
//        String localIp = sp.getString("IP", "47.92.76.67");
//        String localPort = sp.getString("PORT", "8300/POSSrv");
//        String localSktno = sp.getString("SKTNO", "01234");
//        String localStorecode = sp.getString("STORECODE","3");
//
//        String localIp = sp.getString("IP", "39.98.242.166");//47.92.76.67
//        String localPort = sp.getString("PORT", "8306/BFPOSQZJ");//8604/BFPOSQZJ
//        String localSktno = sp.getString("SKTNO", "000001");//700001  000003

        String localIp = sp.getString("IP", "47.92.76.67");//
        String localPort = sp.getString("PORT", "8604/BFPOSQZJ");
        String localSktno = sp.getString("SKTNO", "700001");//  999104

        String localStorecode = sp.getString("STORECODE","1");

        String localPass = sp.getString("KEY","bfv10pos");
        String localSercet = sp.getString("SERCET","bfv10pos");
        ErpCommonData.sktno = localSktno;
        ErpCommonData.storeCode = localStorecode;
        ErpCommonData.key = localPass;
        ErpCommonData.keySercet = localSercet;
        Urls.posAddress = localIp + ":" + localPort;
        PosHttpManager.updateBaseConfigInfo();
        tvIp.setText("IP:" + Urls.posAddress);
        String code = sp.getString("USERSCODES", "999999");
        userList.clear();
        userList.add(code);
    }

//    public void setNoSoftware(EditText et) {
//        CommonUtils.hideSoftInputButWithSelection(et, LoginActivity.this);
//        if(et.equals(etUsername))
//            et.setInputType(EditorInfo.TYPE_CLASS_TEXT);
//        et.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED);
//    }

    @Override
    public void showProgress() {
        dialog.setMessage("正在登陆,请稍后...");
        dialog.show();

    }

    @Override
    public void dismissProgress() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void showLoadFailureMsg(String msg) {
        ToastUtils.show(msg);
    }
    @Override
    public void loginedSuccess(LoadConfig loadConfig) {
        //1.删除本地ticket日志
        deleteLocalLog();
        updateUerCodes(loadConfig.getCashierCode());
        saveUser(etUsername.getText().toString().trim(), etPassword.getText().toString().trim());
        boolean isCateringPos = false;//是否是餐饮pos
        boolean isNoCateringFormat = false;//是否无餐饮业务
        for(Sktconfig sktconfig: ErpCommonData.loadConfig.getSkt().getSktconfigList()){
            if(sktconfig.getLx().equals(SktConfigConstant.SKT_CONFIG_TYPE_SALE)){
                if(sktconfig.getId().equals( SktConfigIdSaleTypeConstant.SKT_CONFIG_CATERING_POS)){
                    isCateringPos = true;
                    if(sktconfig.getValue().equals("-1")){
                        isNoCateringFormat = true;
                    }
                    break;
                }
            }
        }
        if(isCateringPos){
            if(isNoCateringFormat){
                ToastUtils.show("无餐饮业务！");
            }else{
                ErpCommonData.isCatering=true;
                Intent intent = new Intent(LoginActivity.this, CateringMainActivity.class);
                startActivity(intent);
            }


        }else{
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }

    }
    private void updateUerCodes(String code) {
        SharedPreferences pref = getSharedPreferences("LOGIN", 0);
        SharedPreferences.Editor prefEdit = pref.edit();
        LogUtils.d("Login_RYDM",code);
        prefEdit.putString("USERSCODES", code);
        prefEdit.commit();
    }


    private void saveUser(String user, String pwd) {

        Log.i("TAG----user",user+"   pwd: "+pwd);
        SharedPreferences sp = getSharedPreferences("USER", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("user", user);
        editor.putString("pwd", pwd);
        editor.commit();
    }


    private void deleteLocalLog() {
        //1.删除本地7天之前的小票日志
        MessageLog.deleteTikcets();
        //2.删除本地日志一个月前的
        MessageLog.deleteLogFile();
        //3.删除本地奔溃日志日志一个月前的
       // MessageLog.deleLocalCrashLog();
    }

    class CalOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_login_login_act:
                    Login(etUsername.getText().toString().trim(), etPassword.getText().toString().trim());
                    break;
                case R.id.btn_zero_login_act:
                    calInput("0");
                    break;
                case R.id.btn_one_login_act:
                    calInput("1");
                    break;
                case R.id.btn_two_login_act:
                    calInput("2");
                    break;
                case R.id.btn_three_login_act:
                    calInput("3");
                    break;
                case R.id.btn_four_login_act:
                    calInput("4");
                    break;
                case R.id.btn_five_login_act:
                    calInput("5");
                    break;
                case R.id.btn_six_login_act:
                    calInput("6");
                    break;
                case R.id.btn_seven_login_act:
                    calInput("7");
                    break;
                case R.id.btn_eight_login_act:
                    calInput("8");
                    break;
                case R.id.btn_nine_login_act:
                    calInput("9");
                    break;
                case R.id.btn_back_login_act:
                    calBack();
                    break;
                case R.id.btn_sure_login_act:
                    calSure();
                    break;
                case R.id.et_username_login_act:
                    CommonUtils.setOnFocusStatus2(etUsername, etUsername.getText().toString());
                    break;
                case R.id.et_password_login_act:
                    CommonUtils.setOnFocusStatus2(etPassword, etPassword.getText().toString());
                    break;
                default:
                    break;
            }
        }
    }

    public void Login(String uname, String pword) {
        if (MD5Utils.md5(uname).equals(MD5Utils.USER_SETTRING) && MD5Utils.md5(pword).equals(MD5Utils.PASSWORD_SETTRING)) {
            Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
            startActivity(intent);
            return;
        }
        if (etUsername.getText().toString().trim().equals("")) {
            Toast.makeText(LoginActivity.this, "用户不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        loginPresenter.login(uname, pword,CommonUtils.getMac(this));
    }

    private void calInput(String num) {
        String temp = getEditFocus();
        if (temp.equals(FOCUS_FLAG_USERNAME)) {
//            etUsername.append(num);
            CommonUtils.insertEditTextContext(etUsername,num);
        } else if (temp.equals(FOCUS_FLAG_PASSWORD)) {
//            etPassword.append(num);
            CommonUtils.insertEditTextContext(etPassword,num);
        }
    }
    private void calBack() {
        String temp = getEditFocus();
        if (temp.equals(FOCUS_FLAG_USERNAME)) {
            CommonUtils.delectEditTextContext(etUsername);
        } else if (temp.equals(FOCUS_FLAG_PASSWORD)) {
            CommonUtils.delectEditTextContext(etPassword);
        }
    }


    private void calSure() {
        if (getEditFocus().equals(FOCUS_FLAG_USERNAME)) {
            CommonUtils.setOnFocusStatus(etPassword, "");
        } else if (getEditFocus().equals(FOCUS_FLAG_PASSWORD)) {
            if (etPassword.getText().toString().equals("")) {
                CommonUtils.setOnFocusStatus(etUsername, "");
            } else {
                Login(etUsername.getText().toString().trim(), etPassword.getText().toString().trim());
            }
        }
    }
    class BackOnLongClickListener implements View.OnLongClickListener {
        @Override
        public boolean onLongClick(View view) {
            if (view.getId() == R.id.btn_back_login_act) {
                calLongBack();
            }
            return false;
        }
    }
    private void calLongBack() {
        String temp = getEditFocus();
        if (temp.equals(FOCUS_FLAG_USERNAME)) {
            if (!etUsername.getText().toString().equals("")) {
                etUsername.setText("");
            }
        } else if (temp.equals(FOCUS_FLAG_PASSWORD)) {
            if (!etPassword.getText().toString().equals("")) {
                etPassword.setText("");
            }
        }
    }

    private String getEditFocus() {
        if (etUsername.hasFocus()) {
            return FOCUS_FLAG_USERNAME;
        } else if (etPassword.hasFocus()) {
            return FOCUS_FLAG_PASSWORD;
        } else {
            return null;
        }
    }

    private void requestPermissions() {
        if(Build.VERSION.SDK_INT >= 23){
            PermissionGen.with(LoginActivity.this)
                    .addRequestCode(100)
                    .permissions(
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA,
                            Manifest.permission.SYSTEM_ALERT_WINDOW
                    )
                    .request();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
    @PermissionSuccess(requestCode = 100)
    public void doSomething(){
    }
    @PermissionFail(requestCode = 100)
    public void doFailSomething(){
    }

    public void setOffline(){
        SharedPreferences sp = getSharedPreferences("LOGIN", 0);
        boolean cashOffline = sp.getBoolean("ISOFFLINE",false);
        if(cashOffline){
            ckOffline.setChecked(true);
            ErpCommonData.isOffline=true;
        }else{
            ckOffline.setChecked(false);
            ErpCommonData.isOffline=false;
        }
        ckOffline.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences sp = getSharedPreferences("LOGIN", 0);
                SharedPreferences.Editor editor = sp.edit();
                if(isChecked){
                    editor.putBoolean("ISOFFLINE",true);
                    ErpCommonData.isOffline=true;
                }else{
                    editor.putBoolean("ISOFFLINE",false);
                    ErpCommonData.isOffline=false;
                }
                editor.commit();
            }
        });

        if(OfflineManager.isExists()) {
            OfflineManager.updateOffline(LoginActivity.this);
        }
    }
}
